package com.dmall.chapter04.section08;

import com.dmall.chapter02.section09.Graph;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 单源路径问题提前终止的优化
 * @author wx
 * @date 2020-02-25 21:01:14
 */
public class Path {

    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private int s, t;

    public Path(Graph G, int s, int t) {
        G.validateVertex(s);
        G.validateVertex(t);
        this.G = G;
        this.s = s;
        this.t = t;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        for (int i = 0; i < pre.length; i++) {
            pre[i] = -1;
        }
        dfs(s, s);
        for (int i = 0; i < visited.length; i++) {
            System.out.print(visited[i] + " ");
        }
        System.out.println();
    }

    private boolean dfs(int v, int parent) {
        visited[v] = true;
        pre[v] = parent;
        if (v == t) {
            return true;
        }
        for (int w : G.adj(v)) {
            if (!visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isConnected() {
        return visited[t];
    }

    public Iterable<Integer> path() {
        List<Integer> res = new ArrayList<>();
        if (!isConnected()) {
            return res;
        }
        int cur = t;
        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filename = Path.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);

        Path path1 = new Path(g, 0, 6);
        System.out.println("0 -> 6 : " + path1.path());

        Path path2 = new Path(g, 0, 1);
        System.out.println("0 -> 1 : " + path2.path());

        Path path3 = new Path(g, 0, 5);
        System.out.println("0 -> 5 : " + path3.path());

        Path path4 = new Path(g, 0, 0);
        System.out.println("0 -> 0 : " + path4.path());
    }
}
